importScripts('/lib/corn.js')
importScripts('/lib/tools.js')
importScripts('/lib/local_storage_log.js')
importScripts('/lib/config.js')
importScripts('/lib/pusher.js')
importScripts('/lib/open_url_exec_script.js')

importScripts('/apps/crawling_keyword_ranking/background.js')
importScripts('/apps/crawling_top_asin/background.js')
importScripts('/apps/fetch_inventory/background.js')
importScripts('/apps/fetch_ad_invoice/background.js')
importScripts('/apps/fba_shipments/background.js')

// 在这里添加 task
// corn表达式（分 时 日 月 星期）,task name, callback
function schedule(time) {
  corn("* * * * *", '定时清除过期tab', time => clearTab())
  corn("0 7 * * *", '爬取亚马逊新品榜', time => crawlingAllTopAsin())
  corn("30 8 * * *", '拉取库存信息', time => fetchInventory())
  corn("30 0 * * *", '拉取FBA货件明细', time => fetchFbaShipments())
  corn("30 2 * * *", '拉取广告账单', time => fetchAdInvoiceSchedule())
}

async function initialize() {
  let endpoint = await getEndpoint()

  chrome.runtime.onMessage.addListener((request, _, sendResponse) => {
    if (request.action === 'getEndpoint') {
      sendResponse({ endpoint });
      return true; //异步消息
    }
  });

  $pusher.subscribe('chromeCall', endpoint, params => {
    let data = {}

    if (params.pluginMethod == 'fetchInventory') fetchInventory();
    if (params.pluginMethod == 'fetchAdInvoice') fetchAdInvoice(params.link, params.skip);
    if (params.pluginMethod == 'fetchFbaShipments') fetchFbaShipments();
    if (params.pluginMethod == 'crawlingSearchKeywordRanking') crawlingSearchKeywordRanking(params.link);

    post('https://api.miraazzurra.com/pusher/echo', { echoId: params.echoId, endpoint: endpoint, data: data })
  });
}

initialize()
